package com.qdu.dao.impl;

import com.qdu.dao.ExamQuestionDAO;
import com.qdu.entity.ExamQuestion;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class ExamQuestionDAOImpl implements ExamQuestionDAO {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/exam_management_system?serverTimezone=GMT%2B8";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "root";


    @Override
    public List<ExamQuestion> getQuestionsByCourse(String courseName) {
        List<ExamQuestion> questions = new ArrayList<>();
        String sql = "SELECT * FROM exam_questions WHERE course_name =?";
        try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            preparedStatement.setString(1, courseName);
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                while (resultSet.next()) {
                    int questionId = resultSet.getInt("question_id");
                    String questionText = resultSet.getString("question_text");
                    String optionA = resultSet.getString("option_a");
                    String optionB = resultSet.getString("option_b");
                    String optionC = resultSet.getString("option_c");
                    String optionD = resultSet.getString("option_d");
                    String correctAnswer = resultSet.getString("correct_answer");
                    int score = resultSet.getInt("score");
                    String courseNameFromDB = resultSet.getString("course_name");
                    questions.add(new ExamQuestion(questionId, questionText, optionA, optionB, optionC, optionD, correctAnswer, score, courseNameFromDB));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return questions;
    }


    @Override
    public List<String> getAllCourses() {
        List<String> courses = new ArrayList<>();
        String sql = "SELECT DISTINCT course_name FROM courses";
        try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement preparedStatement = connection.prepareStatement(sql);
             ResultSet resultSet = preparedStatement.executeQuery()) {
            while (resultSet.next()) {
                String courseName = resultSet.getString("course_name");
                courses.add(courseName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return courses;
    }
}


